<template>
  
  <div class="article-list">
    <meta name="referrer" content="no-referrer"/>
    <van-pull-refresh v-model="isreFreshLoading" @refresh="onRefresh" :success-text="refreshSuccessText" :success-duration="1500">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
      
        <!-- <van-cell v-for="(article,index) in list" :key="index" :title="article.title" /> -->
        <ArticleItem v-for="(article,index) in list" :key="index" :article="article" ></ArticleItem>
      </van-list>
    </van-pull-refresh>
   
  </div>
</template>
  
<script>
import { getArticles } from "@/api/article"
import ArticleItem from '@/components/article-item'
export default {
  name: "ArticleList",
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      error: false,
      timestamp: "",
      isreFreshLoading:false,
      refreshSuccessText:'刷新成功',
      
    };
  },
  methods: {
    async onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now()
        });
        // console.log(data);

        const { results } = data.data;
        this.list.push(...results);
        // console.log(results)
        this.loading = false;
        if (results.length) {
          this.timestamp = data.data.pre_timestamp;
        } else {
          this.finished = true;
        }
      } catch (err) {
        // console.log("获取数据失败", err);
        this.loading = false;
        this.error = true;
      }
    },
    async onRefresh(){
      try{
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now()
        })
        const { results } = data.data
        this.list.unshift(...results)
        this.isreFreshLoading=false
        this.refreshSuccessText=`刷新成功，更新了${results.length}条数据`
      }catch(err){
        
        this.refreshSuccessText=`刷新失败`
        this.isreFreshLoading=false
      }
    }
  },
  components:{
    ArticleItem
  }
};
</script>
  
<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow-y: auto;
}
.home-container {
  padding-bottom: 100px;
}
</style>